// ------------------------------------
// Actions
// ------------------------------------
import { createAction } from 'http-services'
import * as types from './constant'
import { HttpServices, REDUX_FETCH_TIMEOUT } from 'services/utils'
import * as storageService from 'services/storage'
import _ from 'lodash'
import fetchMock from 'fetch-mock'
import { getToken, setToken } from 'services/token'

export const getInfo = (tag) => dispatch => {
  dispatch(createAction(types.PROTO_FETCH_GETINFO_BEGIN, null))
  setTimeout(() => new Promise(async (resolve, reject) => {
    try {
      const token = getToken()
      const header = {
        Authorization: token
      }
      const result = await HttpServices.GET(`/admins/setting/${tag}`, null, header)
      fetchMock.restore()
      dispatch(createAction(types.PROTO_FETCH_GETINFO_SUCCESS, result))
      resolve(result)
    } catch (error) {
      dispatch(createAction(types.PROTO_FETCH_GETINFO_FAILURE, error))
      reject(error)
    }
  })
  .catch(() => {}), REDUX_FETCH_TIMEOUT)
}

export const setInfo = (tag, content) => dispatch => {
  dispatch(createAction(types.PROTO_FETCH_SETINFO_BEGIN, null))
  setTimeout(() => new Promise(async (resolve, reject) => {
    try {
      const token = getToken()
      const header = {
        Authorization: token
      }
      const result = await HttpServices.POST(`/admins/setting/${tag}`, { content }, header)
      fetchMock.restore()
      dispatch(createAction(types.PROTO_FETCH_SETINFO_SUCCESS, result))
      resolve(result)
    } catch (error) {
      dispatch(createAction(types.PROTO_FETCH_SETINFO_FAILURE, error))
      reject(error)
    }
  })
  .catch(() => {}), REDUX_FETCH_TIMEOUT)
}